package com.itheima.controller;


import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.itheima.controller.ValidateCodeController.LOGIN_KEY;
import static com.itheima.controller.ValidateCodeController.REGISTERED_KEY;

@RestController
@RequestMapping("/member/")
public class MemberController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Reference(timeout = 7000)
    private MemberService memberService;

    @RequestMapping("login")
    public Result login(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        String validateCode = (String)map.get("validateCode");
        String telephone = (String)map.get("telephone");

        Object code = redisTemplate.opsForValue().get(LOGIN_KEY + telephone);
        if (telephone != null && validateCode != null && validateCode.equals(code)) {
            redisTemplate.delete(REGISTERED_KEY + telephone);
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                member = new Member();
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //判断是否是会员 然后自动注册
            //用户存到cookie
            //用户存到redis
            response.addCookie(new Cookie("login_member_telephone",MD5Utils.md5(telephone)));
            redisTemplate.opsForValue().set(telephone, member, 30, TimeUnit.MINUTES);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }

        return new Result(false, validateCode == null || validateCode.length() == 0 ? "验证码为空" : code == null ? "请发送验证码" : "登录失败");
    }
}
